package com.shrio;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class SignGenUtil {

    /**
     * 对检索参数按键值key进行排序，拼接为参数字符串，然后进行MD5加密生成sign
     * sign标签生成方法
     *
     * @param params 检索参数
     * @return
     */
    public static String getSign(HashMap<String, String> params) {
        String sign = "";
        String paramString = "";
        //业务请求参数拼接
        Collection<String> keyset = params.keySet();
        List<String> list = new ArrayList<String>(keyset);
        Collections.sort(list);//对key键值按字典升序排序
        String key = "";
        for (int i = 0; i < list.size(); i++) {
            key = list.get(i);
            if (key != null && !key.trim().equalsIgnoreCase("")) {
                if (key.equalsIgnoreCase("params")) {
                    paramString += params.get(key).trim();
                    paramString += "&";
                } else {
                    paramString += key.trim() + "=" + params.get(key).trim();
                    paramString += "&";
                }
            }
        }
        if (!paramString.equals("")) {
            paramString = paramString.substring(0, paramString.length() - 1);
        }
        System.out.println("[--- DEBUG ---] paramString: " + paramString);
        //进行MD5运算
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            byte[] byteArray = md5.digest(paramString.getBytes("utf-8"));

            StringBuffer md5StrBuff = new StringBuffer();
            //将加密后的byte数组转换为十六进制的字符串,否则的话生成的字符串会乱码
            for (int i = 0; i < byteArray.length; i++) {
                if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                    md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
                } else {
                    md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
                }
            }
            sign = md5StrBuff.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return sign;
    }

    /*
     * 按时间段、站号检索雷达文件 getRadaFileByTimeRangeAndStaId
     */
    public static void main(String[] args) {
        // 服务节点
        String serviceNodeId = "NMIC_MUSIC_CMADAAS";
        //用户ID
        String userId = "USR_BECQ_ZHAOSILIANG";

        //用户密码
        String pwd = "Zhaosi@becq800";

        //接口ID，按站号、时间段检索雷达PUP二进制产品
        String interfaceId = "getRadaFileByTimeRange";
        //数据名
        String dataCode = "RADA_L3_MST_REF_PNG";
        //查询的要素
        String elements = "Datetime,FILE_SIZE,File_URL,FILE_NAME";
        //雷达站号
        String staIds = "Z9230";
        //序列化格式
        //        String dataFormat = "html";
        String dataFormat = "json";
        //查询的时间
        String timeRange = "[20230608235700,20230609015700]";
        //排序
        String orderBy = "Datetime";
        /* 1. 调用方法的参数定义，并赋值 */
        String params = "serviceNodeId=" + serviceNodeId + "&userId=" + userId + "&interfaceId=" + interfaceId + "&dataCode=" + dataCode + "&elements=" + elements + "&staIds=" + staIds + "&timeRange=" + timeRange + "&dataFormat=" + dataFormat + "&orderBy=" + orderBy;
        // + "&limitCnt=10" ; //返回最多记录数：10列化格式 */

        // 拼接timestamp、nonce
//        String timestamp = String.valueOf(System.currentTimeMillis());
        String timestamp = "1686275905967";
//        String nonce = UUID.randomUUID().toString();
        String nonce = "0c413902-4cae-4daf-acbc-ed7ad570d43f";
//        String timestamp1 = "1681657269153";
//        String nonce1 = "1D5CF52E-8C7D-41F6-BF8C-52CB7BFAA56C";
        params += "&timestamp=" + timestamp;
        params += "&nonce=" + nonce;

        // 由参数列表生成sign
        HashMap<String, String> signParam = new HashMap<String, String>();
        signParam.put("serviceNodeId", serviceNodeId);
        signParam.put("userId", userId);
        signParam.put("interfaceId", interfaceId);
        signParam.put("dataCode", dataCode);
        signParam.put("timeRange", timeRange);
        signParam.put("elements", elements);
//        signParam.put("staIds", staIds);
        signParam.put("orderBy", orderBy);
        signParam.put("dataFormat", dataFormat);
        signParam.put("timestamp", timestamp);
        signParam.put("nonce", nonce);
        signParam.put("pwd", pwd);

        System.out.println("[--- DEBUG ---] params: " + params);

        params = "dataCode="+dataCode+"&dataFormat="+dataFormat+"&elements="+elements+"&interfaceId="+interfaceId+"&nonce="+nonce+"&orderBy="+orderBy+"&pwd="+pwd+"&serviceNodeId="+interfaceId+"&staIds=Z9230&timeRange=[20230413010000,20230413020000]&timestamp=1681654354123&userId=BECQ_XXZX_USR_ZM";

        String sign = SignGenUtil.getSign(signParam);
        System.out.println("[--------sign----] " + sign);
        params += "&sign=" + sign;

        /* 2. 调用接口 */
//        Si restUtil = new RestUtil();
//        String rstData = restUtil.getRestData(params);
        //rstData返回为JSON字符串
    }
}